package thread;

/**
 * 线程任务对象
 */
class ThreadTask implements Runnable{
    private Object lock1;
    private Object lock2;
    public ThreadTask(Object lock1, Object lock2)
    {
        this.lock1 = lock1;
        this.lock2 = lock2;
    }
    public void run()
    {
       synchronized (lock1){
           doWork();
           synchronized (lock2){
               doWork();
           }
       }
    }
    private void doWork()
    {
        System.out.println(Thread.currentThread().getName()+"->working....");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class ThreadLockDemo01 {
    public static void main(String[] args) {
        Object lock1=new Object();
        Object lock2=new Object();
        Thread t1=new Thread(new ThreadTask(lock1,lock2),"t1");
        Thread t2=new Thread(new ThreadTask(lock2,lock1),"t2");
        t1.start();
        t2.start();
    }
}
